﻿using System.Collections.Generic;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using Inovout.Gis.Geometry;
using Inovout.Gis;

namespace Inovout.ArcGis
{
    public class FeatureLayerInfo : LayerInfo, IGeometryLayerInfo
    {
        #region Constructor
        private ArcGisTable table;
        internal protected FeatureLayerInfo(ArcGisTable table)
            : this(table.ArcTable as IFeatureLayer)
        {
            table.Layer = this;
            this.table = table;
        }
        public FeatureLayerInfo(IFeatureLayer arcFeatureLayer) :
            base(arcFeatureLayer)
        {
        //    IFeatureCursor c = arcFeatureLayer.Search(null, true);
        //    IFeature f = c.NextFeature();
        //    if (f != null)
        //    {
        //        ((IWorkspaceEdit)((IDataset)arcFeatureLayer).Workspace).StartEditing(false);
        //        ((IWorkspaceEdit)((IDataset)arcFeatureLayer).Workspace).StartEditOperation();
        //        f.Store();
        //        ((IWorkspaceEdit)((IDataset)arcFeatureLayer).Workspace).StopEditOperation();
        //        ((IWorkspaceEdit)((IDataset)arcFeatureLayer).Workspace).StopEditing(false);
        //    }
        }

        #endregion

        protected IGisTable Table
        {
            get { return table; }
        }

        protected override string GetName()
        {
            if(table==null)
            {
                IDataset dataset = base.arcLayer as IDataset;
                string name = dataset.BrowseName;
                if (name.Contains("."))
                {
                    int lastDotIndex = name.LastIndexOf(".");
                    name = name.Substring(lastDotIndex + 1, name.Length - lastDotIndex - 1);
                }
                return name;
            }
            else
            {
                return table.Name;
            }
        }

        public static string GetLayerName(IDataset faatureDataset)
        {
            string name = faatureDataset.BrowseName;
            if (name.Contains("."))
            {
                int lastDotIndex = name.LastIndexOf(".");
                name = name.Substring(lastDotIndex + 1, name.Length - lastDotIndex - 1);
            }
            return name;
        }



        #region Geometries
        private List<IGeometryInfo> geometries;
        public IGeometryInfo[] Geometries
        {
            get
            {
                if (geometries == null)
                {
                    geometries =new List<IGeometryInfo>( Table.GetGeometryInfos());
                }
                return geometries.ToArray();
            }
        }
        #endregion
    }
}
